using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[DefaultExecutionOrder(-100)]
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public GameObject candy;
    public GameObject Eater;
    public GameObject Game;
    private Transform bgImageTs;
    private Transform PauseButtonTs;
    private Transform ReplayButtonTs;
    private Transform BackButtonTs;
    public AudioSource audioSource;
    public List<AudioClip> audioClips = new List<AudioClip>();
    private bool isPlayLostAudio;
    public bool win;
    public bool lost;
    private float speed;
    public int starCount = 0;

    public int StarCount
    {
        get => starCount;
        set
        {
            starCount = value;
            audioSource.clip = audioClips[starCount - 1];
            audioSource.Play();
        }
    }

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
    }

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        playPreAudio();
        GameObject rootGo = GameObject.Find("Root");
        Transform canvasTs = rootGo.transform.Find("Canvas").transform;
        // 返回按钮
        BackButtonTs = canvasTs.Find("BackButton");
        if (BackButtonTs != null)
        {
            Button backButton = BackButtonTs.GetComponent<Button>();
            backButton.onClick.AddListener(OnBackClick);
        }
        // 暂停按钮
        PauseButtonTs = canvasTs.Find("PauseButton");
        if (PauseButtonTs != null)
        {
            Button PauseButton = PauseButtonTs.GetComponent<Button>();
            PauseButton.onClick.AddListener(OnPauseClick);
        }
        // 重玩按钮
        ReplayButtonTs = canvasTs.Find("ReplayButton");
        if (ReplayButtonTs != null)
        {
            Button ReplayButton = ReplayButtonTs.GetComponent<Button>();
            ReplayButton.onClick.AddListener(OnRestartClick);
        }

        Game = GameObject.Find("Game");
        bgImageTs = canvasTs.Find("BgImage");
    }

    private void playPreAudio()
    {
        audioSource.clip = audioClips[audioClips.Count - 2];
        audioSource.Play();
    }

    private void playLostAudio()
    {
        audioSource.clip = audioClips[audioClips.Count - 1];
        audioSource.Play();
        isPlayLostAudio = true;
    }

    private void OnBackClick()
    {
        SceneManager.LoadScene(1);
    }

    private void OnPauseClick()
    {
        Time.timeScale = 0;

        resetPanelParameter();
        PanelManager.Open<PausePanel>();
    }

    private void OnRestartClick()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

    // Update is called once per frame
    void Update()
    {
        if (win)
            return;
        if (lost && isPlayLostAudio == false)
        {
            playLostAudio();
            Invoke("OnRestartClick", 0.8f);
            return;
        }
        CheckWin();
    }

    private void CheckWin()
    {
        if (candy == null || candy.transform == null)
        {
            return;
        }

        float distance = Vector2.Distance(Eater.transform.position, candy.transform.position);
        Debug.Log(Eater.transform.position);
        Debug.Log(candy.transform.position);

        if (distance < 2f)
        {
            Vector2.MoveTowards(
                candy.transform.position,
                Eater.transform.position,
                speed * Time.deltaTime
            );
            Debug.Log("distance");
            Debug.Log(distance);
            if (distance < 1f)
            {
                EatCandy();
            }
        }
    }

    private void EatCandy()
    {
        // RopeManager.instance.SendMessage("removeHingeJoint2D");
        RopeManager.instance.SendMessage("removeCandyHingeJoint2D");
        win = true;
        candy.SetActive(false);
        Destroy(candy);
        // Debug.Log("Open");
        SaveStars();
        audioSource.clip = audioClips[3];
        audioSource.Play();
        Invoke("hiddenGamePanel", 2.5f);
        Invoke("winPanelShow", 2.5f);
    }

    private void hiddenGamePanel()
    {
        Game.SetActive(false);
        Image BgImage = bgImageTs.GetComponent<Image>();
        BgImage.enabled = true;

        Image BackButtonImage = BackButtonTs.GetComponent<Image>();
        BackButtonImage.enabled = false;
    }

    private void SaveStars()
    {
        string name = SceneManager.GetActiveScene().name;
        // 上一次的最佳成绩
        int count = PlayerPrefs.GetInt(name);
        // 上次累计的总星星
        int totalCount = PlayerPrefs.GetInt("ToTal");
        if (PlayerPrefs.HasKey(name))
        {
            // 此次更佳
            if (starCount > count)
            {
                PlayerPrefs.SetInt(name, starCount);
                int newTotalCount = totalCount - count + starCount;
                // 此次累计的星星
                PlayerPrefs.SetInt("ToTal", newTotalCount);
            }
        }
        else
        {
            // 第一次玩
            PlayerPrefs.SetInt(name, starCount);
            int newTotalCount = totalCount + starCount;
            PlayerPrefs.SetInt("ToTal", newTotalCount);
        }
    }

    private void resetPanelParameter()
    {
        PanelManager.isInit = false;
        PanelManager.Init();
    }

    private void winPanelShow()
    {
        resetPanelParameter();
        PanelManager.Open<WinPanel>();
    }

    private void turnLost()
    {
        lost = true;
    }
}
